<?php
/**
 * 微信（企业号）
 * Enter description here ...
 * @author Administrator
 *
 */
namespace Weixin\Controller;
include_once APP_PATH.'Weixin/Common/Qiye/WXBizMsgCrypt.php'; //加载微信函数包
vendor('Weixin.Qiye.WeixinQiye'); //加载微信函数包
class WeixinQiyeController extends \WeixinQiye{
	public function __construct(){
		parent::__construct();
        $this->redirect_uri = U('Weixin/WeixinQiye/callback');
	}


	public function index(){
		//获取员工信息
		$state = $_GET['state'];
		$userid = $this->getUserid();
            if (empty($userid)){
			die('login error');
		}else {
			//是否为本公司员工
			$_SESSION['wxid'] = $userid;
			header('location:'.$state);
		}
	}


    /**
     * 回调地址
     * @param string $success_url 成功后跳转地址
     */
    function callback($success_url=''){
        if(empty($success_url)){
            $success_url = U('Weixin/WeixinQiye/login');
        }
        //获取员工信息
        $userid = $this->getUserid();
        if (empty($userid)){
            die('login error');
        }else {
            //是否为本公司员工
            $_SESSION['wxid'] = $userid;
            header('location:'.$success_url);
        }
    }

    /**
     * 判断userid对应用户是否存在
     */
    public function login(){
        $userid = $_SESSION['wxid'];
        $pk_id = M('user')->where('userid = "%s" AND status = 0',$userid)->getField('pk_id');
        if(!$pk_id){
            $pk_id = self::create_user();
            if(!$pk_id){
                header("Content-Type: text/html; charset=utf-8");
                $this->castError('创建用户失败');
            }
        }
        $_SESSION['user_id'] = $pk_id;
//        $this->display('Weixin@Index:SelectQuery');       //渲染模板
    }

    /**
     * 创建用户信息
     * @return bool|mixed
     */
    private function create_user(){
        $userid = $_SESSION['wxid'];
        $wxUserInfo = $this->getUserInfo($userid);
        $data['name'] = $wxUserInfo['name'];
        $data['userid'] = $wxUserInfo['userid'];
        $data['head_img'] = $wxUserInfo['avatar'];
        $data['create_time'] = date('Y-m-d H:i:s');
        $pk_id = M('user')->add($data);
        if(!$pk_id){
            return $pk_id;
        }else{
            return false;
        }

    }


    /**
     * 微信授权入口
     * @param string $success_url
     * @param string $scope 授权方式 info详细,base基本
     */
    function oauth2_run($success_url='',$scope='base'){
        $scope = $scope == 'base' || !$scope ? 'snsapi_base' : 'snsapi_userinfo';
        !$this->redirect_uri && die('未设置redirect_uri');
        $this->redirect_uri = $success_url ? urlencode($this->redirect_uri.'?success_url='.$success_url.'&scope='.$scope) : urlencode($this->redirect_uri);
        die(header('location:https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$this->corpId.'&redirect_uri='.$this->redirect_uri.'&response_type=code&scope='.$scope.'&state=STATE#wechat_redirect'));
    }
	
	
	/**
	 * 入口（接收数据）
	 * Enter description here ...
	 */
	public function run(){
		$this->handleMessage();
	}
	
	
	/**
	 * 处理消息
	 * Enter description here ...
	 * @param unknown_type $sMsg 消息
	 */
	public function handleMessage(){
        // 网址接入验证
        writeToFile($_GET,'./Public/','1111.txt','a+b');

        $this->checkVerifyUrl();

		//个人查询
		if ($this->request['agentid'] == 8){
			$stfid = $this->request['fromusername'];
			switch ($this->request['eventkey']) {
				//积分查询
				case 'SELF_SCORE':
					$integral = M('staff')->where('pk_id = %d',$stfid)->getField('integral');
					$message = '您当前的泉值为'.$integral.'分，请再接再厉';
					$this->responseText($message);
				break;
				
				//考勤查询
				case 'SELF_ATTENDANCE':
					//获取考勤天数
					$day_num = $this->getStaffWorkInfo($stfid);
    				$message = '您上月考勤天数为'.$day_num.'天。';
					$this->responseText($message);
				break;
				
				//个人护理费查询
				case 'SELF_NURSE_FEE':
					//获取护理费
					$fee = $this->getStaffWorkInfo($stfid,2);
					$message = '您上月护理费为'.$fee.'元。';
					$this->responseText($message);
				break;
			}
		}
	}
	
	
	/**
	 * 获取员工考勤、护理费
	 * Enter description here ...
	 * @param unknown_type $stfid 员工ID
	 * @param unknown_type $type 1获取考勤  2获取护理费
	 */
	public function getStaffWorkInfo($stfid,$type=1){
		$day_num = 0; //默认0天
		$fee = 0; //默认0元
		$month = date('m',strtotime('-1 month')); //上月月数
		$wMonth = date('Y-m',strtotime('-1 month')); //上月日期
		//获取一对一考勤天数

					
					
		//整体护理天数
		$department_sub = M('department_sub');
		$attendance_log = M('attendance_log');
		$attendance_log_info = M('attendance_log_info');
		$check_dpt_record = M('check_dpt_record');
		$subInfo = $department_sub->where("FIND_IN_SET($stfid,attendant) > 0 OR fk_stf_z_id = $stfid")->select();
		if (!empty($subInfo)){
			//有常驻科室
    		foreach ($subInfo as $skey => $svalue){
		    	//获取整体考勤记录 ID
		    	$awhere['fk_dub_id'] = $svalue['pk_id'];
		    	$awhere['date'] = array('like',"$wMonth%");
		    	$aidArr = $attendance_log->where($awhere)->getField('pk_id',true);
		    	if (!empty($aidArr)){
		    		//获取整体考勤天数
			    	$atwhere['fk_alg_id'] = array('in',$aidArr);
	    			$atwhere['fk_stf_id'] = $stfid;
	    			$atwhere['type'] = array('neq',0);
	    			$alg_num = $attendance_log_info->where($atwhere)->count();
	    						
	    			//获取连班记录数
	    			$atwhere['type'] = 3;
	    			$lianban = $attendance_log_info->where($atwhere)->count();
	    			if ($lianban>0){
	    				$alg_num += $lianban;
	    			}
	    						
	    			//获取半天记录数
	    			$atwhere['type'] = 4;
	    			$bantian_num = $attendance_log_info->where($atwhere)->count();
	    			if ($bantian_num > 0){
	    				$alg_num -= $bantian_num;
	    				$bantian_num  = $bantian_num * 0.5;
		    			$alg_num += $bantian_num;
	    			}
	    			
					$month = date('m',strtotime('-1 month')); //上月月数
					$wMonth = date('Y-m',strtotime('-1 month')); //上月日期
					
					if ($type == 1){
						//护理费=出勤天数 * 平均每天护理费(每月科室核定中的每天平均护理费)
						$day_num = $this->getStaffAttendance($stfid);
				    	$cMap['month'] = $month;
				    	$cMap['fk_dub_id'] = $svalue['pk_id'];
				    	$dub_total = $check_dpt_record->where($cMap)->getField('dub_total');
				    	$nursefee = $dub_total*$alg_num;
				    	$fee += $nursefee;
					}else {
						$day_num += $alg_num;
					}
		    	}
    		}
    	}
    	return $type == 1 ? $day_num : $fee;
	}
	
	
	/**
	 * 获取员工上月护理费
	 * Enter description here ...
	 * @param unknown_type $stfid 员工ID
	 */
	public function getStaffNurseFee($stfid){


	}
	
	
	
	/**
	 * 生成菜单外部地址
	 * Enter description here ...
	 */
	public function create_url(){
		$url = U(I('get.url'));
		$url = urlencode($url);
		echo 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='.C('CORP_ID').'&redirect_uri='.U('WeixinQiye/index').'&response_type=code&scope=snsapi_base&state='.$url.'#wechat_redirect';
	}
}
?>